package com.king.oa.view.action;

import java.util.HashSet;
import java.util.List;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.king.oa.base.BaseAction;
import com.king.oa.domain.Privilege;
import com.king.oa.domain.Role;
import com.king.oa.util.QueryHelper;
import com.opensymphony.xwork2.ActionContext;

@Controller
@Scope("prototype")
public class RoleAction extends BaseAction<Role> {

	private static final long serialVersionUID = 7156995871460582780L;

	private Long[] privilegeIds;
	

	/**列表*/
	public String list() throws Exception{
//		List<Role> roleList = roleService.findAll();
//		ActionContext.getContext().put("roleList", roleList);
		
		new QueryHelper(Role.class, "r").prepaerePageBean(roleService, pageNum, pageSize);;
		
		return "list";
	}
	
	/**删除*/
	public String delete() throws Exception{
		Role role = roleService.findById(this.model.getId());
		if(role!=null){
			roleService.delete(this.model.getId());
		}
		return "toList";
	}
	
	/**添加页面*/
	public String addUI() throws Exception{
		return "saveUI";
	}
	
	/**添加*/
	public String add() throws Exception{
		roleService.save(model);
		return "toList";
	}
	
	/**修改页面*/
	public String editUI() throws Exception{
		//准备回显数据
		this.model = roleService.findById(model.getId());
		
		return "saveUI";
	}
	
	/**修改*/
	public String edit() throws Exception{
		//1、从数据库获取原对象
		Role role = roleService.findById(this.model.getId());
		
		//2、设置新数据
		role.setName(this.model.getName());
		role.setDescription(this.model.getDescription());
		
		//3、更新到数据库
		roleService.update(role);
		return "toList";
	}	
	
	/**设置权限页面*/
	public String setPrivilegeUI() throws Exception{
		//准备回显数据
		this.model = roleService.findById(model.getId());
		if(model.getPrivileges() != null){
			privilegeIds = new Long[model.getPrivileges().size()];
			int index = 0;
			for(Privilege privilege : model.getPrivileges())
				privilegeIds[index++] = privilege.getId();
		}
		List<Privilege> privilegeList = privilegeService.findTopList();
		ActionContext.getContext().put("privilegeList", privilegeList);
		
		return "setPrivilegeUI";
	}
	
	/**设置权限*/
	public String setPrivilege() throws Exception{
		//1、从数据库获取原对象
		Role role = roleService.findById(this.model.getId());
		
		//2、设置新数据
		List<Privilege> privilegeList = privilegeService.findByIds(privilegeIds);
		role.setPrivileges(new HashSet<>(privilegeList));
		
		//3、更新到数据库
		roleService.update(role);
		
		return "toList";
	}

	public Long[] getPrivilegeIds() {
		return privilegeIds;
	}

	public void setPrivilegeIds(Long[] privilegeIds) {
		this.privilegeIds = privilegeIds;
	}
	
}
